package com.example.privacy;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;


import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    private RadioGroup rg;
    private String type = "0";
    private EditText etusername;
    private EditText etpassword;
    private Button registerbutton;
    private Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        rg = (RadioGroup)findViewById(R.id.radio_group);
        etusername = (EditText)findViewById(R.id.register_input_username);
        etpassword = (EditText)findViewById(R.id.register_input_password);
        registerbutton = (Button)findViewById(R.id.register_button);
        registerbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRegister();
            }
        });
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radio0:
                        type = "0";
                        break;
                    case R.id.radio1:
                        type = "1";
                        break;
                    case R.id.radio2:
                        type = "2";
                        break;
                }
            }
        });
    }

    private void doRegister(){
        String username = etusername.getText().toString();
        String password = etpassword.getText().toString();
        if(username==null||username.equals("")){
            Toast.makeText(this,"用户名不可为空",Toast.LENGTH_SHORT).show();
            return;
        }
        if(password==null||password.equals("")){
            Toast.makeText(this,"密码不可为空",Toast.LENGTH_SHORT).show();
            return;
        }
        Register(username,password,type);
    }

    private void Register(final String uname, final String upassword, final String ty){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final MediaType JSON = MediaType.get("application/json; charset=utf-8");
                String url = getString(R.string.baseUrl)+"/register";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                String json = String.format("{\"username\":\"%s\",\"password\":\"%s\",\"type\":\"%s\"}", uname,upassword,ty);
                System.out.println(json);
                RequestBody body = RequestBody.create(json, JSON);
                System.out.println(body.toString());
                final Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                System.out.println("运行");
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                        String result = response.body().string();
                        JSONObject jo = new JSONObject(result);
                        String name = jo.getString("username");
                        if(name.equals(uname)){
                            //去登陆页面
//                            showToast(RegisterActivity.this,"注册成功，请登录");
                            RegisterActivity.this.finish();
                        }
                    }
                    response.body().close();
                }catch (JSONException je){
                    showToast(RegisterActivity.this,"用户名已被注册");
                    System.out.println(je.getMessage().toString());
                }catch (Exception e){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(RegisterActivity.this, "服务器连接失败,服务器已下线，当前服务器IP"+getString(R.string.baseUrl),Toast.LENGTH_LONG).show();
                        }
                    });
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }

    public void showToast(Context context, String text) {
        Looper myLooper = Looper.myLooper();
        if (myLooper == null) {
            Looper.prepare();
            myLooper = Looper.myLooper();
        }

        if (toast == null) {
            toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }
        toast.show();
        if ( myLooper != null) {
            Looper.loop();
            myLooper.quit();
        }
    }
}